Array.prototype.findHashIndex = (arr, key) => {
    for (var i = 0; i < arr.length; i++) {
        if (key === arr[i][0]) {
            return i;
        }
    }
    return -1;
};

class LxHashTable {
    constructor() {
        this.storage = [];
        this.count = 0;
        this.limit = this.getMinPrime(7);
    }

    // 判断质数
    isPrime(num) {
        if (num < 2) return false;
        var temp = parseInt(Math.sqrt(num));
        for (var i = 2; i <= temp; i++) {
            if (num % i === 0) {
                return false;
            }
        }
        return true;
    }

    getMinPrime(num) {
        while (!this.isPrime(num)) {
            num++;
        }
        return num;
    }

    hashFunc(str, size) {
        var hashCOde = 0;
        for (var i = 0; i < str.length; i++) {
            hashCOde = hashCOde * 37 + str.charCodeAt(i);
        }
        return hashCOde % size;
    }

    push(key, value) {
        let index = this.hashFunc(key, this.limit);
        if (this.storage[index]) {
            let ishas = this.storage[index].find((item) => key === item[0]);
            if (ishas) {
                ishas[1] = value;
            } else {
                this.storage[index].push([key, value]);
            }
        } else {
            this.storage[index] = [[key, value]];
        }
        this.count++;
    }

    get(key) {
        let index = this.hashFunc(key, this.limit);
        if (this.storage[index]) {
            let ishas = this.storage[index].find((item) => key === item[0]);
            if (ishas) {
                return ishas[1];
            }
            return null;
        }
        return null;
    }

    remove(key) {
        let index = this.hashFunc(key, this.limit);
        if (this.storage[index]) {
            let ishas = this.storage[index].findHashIndex(this.storage[index], key);
            if (ishas != -1) {
                this.storage[index].splice(ishas, 1);
                this.count--;
            }
            return false;
        }
        return false;
    }

    isEmpty() {
        return !this.count;
    }

    resize(newLimit) {
        var oldStorage = this.storage;
        this.count = 0;
        this.limit = this.getMinPrime(newLimit);
        console.log(this.limit);
        this.storage = [];
        oldStorage.forEach((bucket) => {
            bucket &&
            bucket.forEach((bucketItem) => {
                this.push(bucketItem[0], bucketItem[1]);
            });
        });
    }
}

var hashTable = new LxHashTable();
hashTable.push("xx", "11");
hashTable.push("xxx", "11");
hashTable.resize(99);
// hashTable.remove("xx");
console.log(hashTable.storage);
